
package com.lgcns.android2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class PhotoActivity extends Activity implements OnClickListener {

    public static final String TAG = MainActivity.TAG;

    private Gallery mGallery;
    
    private TextView mName;
    private TextView mTel;
    private TextView mEmail;
    private TextView mLocation;
    private TextView mJob;
    private TextView mManager;
    private ImageView mImageCamera;
    private ImageView mImageSms;
    private ImageView mImageTel;
    
    private QuickAction mQuickAction;
    private ActionItem mCameraAction;
    private ActionItem mGalleryAction;

    private ImageView mSelectedImageView;
    private int mProfileId;
    private Uri mImageCaptureUri;

    private PhotoCursorAdapter mAdapter;

    private static final String[] PROJECTION = {
        Constants._ID,
        Constants.ID_NUM,
        Constants.TITLE,
        Constants.NAME,
        Constants.TEL,
        Constants.EMAIL,
        Constants.LOCATION,
        Constants.JOB,
        Constants.PHOTO,
        Constants.MANAGER
        };

    private static final String SORT_ORDER = Constants.TITLE_CODE + ", " + Constants.NAME;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.profile_photo);

        // initialize UI and listeners
        initialize();

        // Attach cursor adapter to Gallery View
        Cursor c = managedQuery(ProfileProvider.PROFILES_CONTENT_URI, PROJECTION, null, null, SORT_ORDER);
        mAdapter = new PhotoCursorAdapter(this, c);
        
        mGallery.setAdapter(mAdapter);
        mGallery.setCallbackDuringFling(false);
        mGallery.setSelection(0, true);

        // Set a default member in detail view
        View firstView = mGallery.getChildAt(0);

        if (firstView != null) {
            changeDetailView(firstView);
        }
    }

    private void initialize() {
        // Setup member variables
        mGallery = (Gallery) findViewById(R.id.photoGallery);
        mName = (TextView) findViewById(R.id.name);
        mTel = (TextView) findViewById(R.id.tel);
        mEmail = (TextView) findViewById(R.id.email);
        mLocation = (TextView) findViewById(R.id.location);
        mJob = (TextView) findViewById(R.id.job);
        mManager = (TextView) findViewById(R.id.manager);
        mImageCamera = (ImageView) findViewById(R.id.imgCamera);
        mImageSms = (ImageView) findViewById(R.id.imgSms);
        mImageTel = (ImageView) findViewById(R.id.imgTel);

        // Setup action buttons
        mCameraAction = new ActionItem();
        mCameraAction.setId(R.id.cameraPopup);
        mCameraAction.setTitle("Camera");
        mCameraAction.setIcon(getResources().getDrawable(R.drawable.ic_camera));
        mCameraAction.setOnClickListener(this);

        mGalleryAction = new ActionItem();
        mGalleryAction.setId(R.id.galleryPopup);
        mGalleryAction.setTitle("Gallery");
        mGalleryAction.setIcon(getResources().getDrawable(R.drawable.ic_gallery));
        mGalleryAction.setOnClickListener(this);

        // Attach listeners
        mImageCamera.setOnClickListener(this);
        mImageSms.setOnClickListener(this);
        mImageTel.setOnClickListener(this);

        mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                changeDetailView(view);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mGallery.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                changeDetailView(view);
            }
        });

        mGallery.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                PhotoCursorAdapter.ViewCache cache = (PhotoCursorAdapter.ViewCache) view.getTag();
                ProfileItem item = cache.item;

                Intent intent = new Intent(PhotoActivity.this, PhotoEnlagerActivity.class);
                intent.putExtra(Constants.ID_NUM, item.idNum);

                startActivity(intent);
                return true;
            }
        });
    }
    
    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.imgSms:
                startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mTel.getText())));
                break;

            case R.id.imgTel:
                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mTel.getText())));
                break;

            case R.id.imgCamera:
                mQuickAction = new QuickAction(v);
                mQuickAction.addActionItem(mCameraAction);
                mQuickAction.addActionItem(mGalleryAction);
                mQuickAction.show();
                break;

            case R.id.cameraPopup: 
            	mQuickAction.dismiss();
                doTakePhotoAction();
                break;

            case R.id.galleryPopup:
            	mQuickAction.dismiss();
                doPickAlbumAction();
                break;

            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.photo, menu);
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return applyOptionChoice(item) || super.onOptionsItemSelected(item);
    }

    /**
     * Menu option 에 선택에 따른 분기 처리
     * 
     * @param item
     * @return
     */
    private boolean applyOptionChoice(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.save_contact :
                Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
                intent.putExtra(ContactsContract.Intents.Insert.NAME, mName.getText());
                intent.putExtra(ContactsContract.Intents.Insert.EMAIL, mEmail.getText());
                intent.putExtra(ContactsContract.Intents.Insert.PHONE, mTel.getText());
                startActivity(intent);
                return true;
            default:
                break;
        }
        return false;
    }

    /**
     * 선택된 인원에 대한 세부 정보를 Detail view에 표시 
     * 
     * @param v
     */
    private void changeDetailView(View view) {
        mSelectedImageView = (ImageView) view.findViewById(R.id.photo);

        PhotoCursorAdapter.ViewCache cache = (PhotoCursorAdapter.ViewCache)view.getTag();
        ProfileItem item = cache.item;

        mName.setText(item.name + " " + item.title);
        mManager.setText(item.manager);
        mTel.setText(item.tel);
        mEmail.setText(item.email);
        mLocation.setText(item.location);
        mJob.setText(item.job);
        
        mProfileId = item.idNum;
        
        if (item.manager != null && !"".equals(item.manager)) {
            mManager.setVisibility(View.VISIBLE);
        } else {
            mManager.setVisibility(View.GONE);
        }
    }

    /**
     * Camera appl. 로부터 이미지를 캡쳐 
     */
    private void doTakePhotoAction() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        String url = "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), url));

        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.PICK_FROM_CAMERA);
    }

    /**
     * Gallery appl. 로부터 이미지를 Pick
     */
    private void doPickAlbumAction() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
        startActivityForResult(intent, Constants.PICK_FROM_ALBUM);
    }

    /**
     * 
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            // Gallery album으로부터 pick
            case Constants.PICK_FROM_ALBUM: {
                mImageCaptureUri = data.getData();

                // Gallery에서 pick한 image uri에 대해 CROP 하도록 함
                // 아래 PICK_FROM_CAMERA 와 동일 로직 
            }

            // Camera로부터 capture
            case Constants.PICK_FROM_CAMERA: {
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(mImageCaptureUri, "image/*");

                // Crop ouput size 및 ratio 지정
                intent.putExtra("outputX", 215);
                intent.putExtra("outputY", 242);
                intent.putExtra("aspectX", 3);
                intent.putExtra("aspectY", 4);
                intent.putExtra("scale", true);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, Constants.CROP_PHOTO);

                break;
            }

            // Album 또는 Camera 로부터 받은 이미지를 Crop
            case Constants.CROP_PHOTO: {
                final Bundle extras = data.getExtras();

                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");

                    // 해당 cacheOutput을 data 밑에 사번.jpg로 저장
                    FileOutputStream fos = null;

                    try {
                        fos = openFileOutput(mProfileId + ".jpg", Context.MODE_PRIVATE);
                        photo.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                    } catch (FileNotFoundException e) {
                        Log.e(TAG, "File not found exception");
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                ;
                            }
                        }
                    }

                    // adapter 에서 해당 인원의 bitmap cache의 갱신
                    mAdapter.invalidateBitmapCache(mProfileId);

                    // ImageView update
                    mSelectedImageView.setImageBitmap(photo);
                }

                File f = new File(mImageCaptureUri.getPath());
                if (f.exists()) {
                    f.delete();
                }

                break;
            }
        }
    }

}
